package cn.kiliter.web.servlet;

import cn.kiliter.model.Order;
import cn.kiliter.model.OrderItem;
import cn.kiliter.model.Product;
import cn.kiliter.model.User;
import cn.kiliter.serviece.OrderService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@WebServlet("/createOrder")
public class CreateOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        //设置id
        Order order=new Order();
        try {
            BeanUtils.populate(order,request.getParameterMap());
            order.setUser(user);
            order.setId(UUID.randomUUID().toString());
            Map<Product,Integer> cart = (Map<Product, Integer>) request.getSession().getAttribute("cart");
            List<OrderItem> list = new ArrayList<OrderItem>();
            for(Map.Entry<Product,Integer> entry : cart.entrySet()){
                OrderItem oi = new OrderItem();
                oi.setBuynum(entry.getValue());
                oi.setProduct(entry.getKey());
                oi.setOrder(order);
                list.add(oi);
            }
            order.setItems(list);
            order.setOrdertime(new Date());
            OrderService service=new OrderService();
            service.addOrder(order);
            request.getSession().removeAttribute("cart");
            response.sendRedirect(request.getContextPath()+"/paysuccess.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
